#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
# 作者：肖银皓
# 创建：2021-06-13
# 用意：硬件接口驱动封装和视频流封装
"""
from picamera.array import PiRGBArray
from picamera import PiCamera
import RPi.GPIO as GPIO
import time
import cv2
import copy
from flask import Flask, render_template, Response

app = Flask(__name__)
time_stamp = time.time()
camera = None
image = None
image_capture = None
img_path = "./1.jpg" # 检测图片存放路径
report_path = "./report/" # 报告结果存放路径

def RunCamera(camera):
    """
    初始化并运行摄像头并展示视频窗口。拍摄按钮按下的时候拍摄照片。
    :return: 返回捕捉到的相片的矩阵
    """
    # 初始化树莓派树莓派
    camera.resolution = (640, 480)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(640, 480))
    # 摄像头预热时间
    time.sleep(0.1)
    global image

    # 对摄像头捕捉到的每一帧进行循环
    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
        # 把每一帧信息存入image
        image = frame.array
        # 展示帧
        (flag, encodedImage) = cv2.imencode(".jpg", frame.array)
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')
        # 清除缓存流，为下一帧采集腾出空间
        rawCapture.truncate(0)


def TurnOnRed():
    """
    设置BCM 18管脚高电平点亮红灯
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)
    GPIO.output(18, 1)

def TurnOffRed():
    """
    设置BCM 18管脚低电平熄灭红灯
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)
    GPIO.output(18, 0)

def TurnOnWhite():
    """
    设置BCM 23管脚高电平点亮白灯
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(23, GPIO.OUT)
    GPIO.output(23, 1)

def TurnOffWhite():
    """
    设置BCM 23管脚低电平熄灭白灯
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(23, GPIO.OUT)
    GPIO.output(23, 0)

def TurnOnBeep():
    """
    设置BCM 24管脚高电平开启蜂鸣器
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(24, GPIO.OUT)
    GPIO.output(24, 1)

def TurnOffBeep():
    """
    设置BCM 24管脚低电平关闭蜂鸣器
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(24, GPIO.OUT)
    GPIO.output(24, 0)

def ButtonDown(channel):
    """
    检测用户是否按下按钮（BCM 管脚25）
    如果按下按钮则拍照，并且保存到相应检测位置
    """
    global time_stamp  # 去抖动
    global image # 捕捉图片
    global image_capture
    time_now = time.time()
    if (time_now - time_stamp) >= 0.6:
        if image is not None:
            print("拍照！")
            image_capture = copy.copy(image)
            cv2.imwrite(img_path, image_capture)
    time_stamp = time_now

# 25号BCM 按钮
def InitButton():
    """
    初始化按钮，BCM管脚25
    """
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.add_event_detect(25, GPIO.RISING, callback=ButtonDown)

@app.route('/')
def index():
    return render_template('video.html')

@app.route('/video_feed')
def video_feed():
    global camera
    if camera is None:
        camera = PiCamera()
        return Response(RunCamera(camera),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
    else:
        camera.close()
        camera = PiCamera()
        return Response(RunCamera(camera),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

def RunProcess():
    """
    线程中打包运行函数
    """
    InitButton()
    app.run(host='0.0.0.0', port=8080, debug=True)